//
//  TokDataBase.m
//  tok
//
//  Created by sijian on 12-7-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TokDataBase.h"
#import "FMDatabase.h"
#import "FMResultSet.h"

static TokDataBase * sharedInstance = nil; 
static FMDatabase *dbo = nil;
@interface TokeDataBase
-(void)copyDatabaseIfNeeded;
-(id)initSingleton;
@end


@implementation TokDataBase
@synthesize dbPath = _dbPath;

#pragma mark - init
- (void ) initAppDataBase {
    //Using NSFileManager we can perform file system operati*****.
    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSError *error;
    //获取工作路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    //构建数据库文件路径
    NSString *dbTargetPath = [documentsDir stringByAppendingPathComponent:@"tok.db"];
    
    //判断数据库文件是否存在
    BOOL success = [fileManager fileExistsAtPath:dbTargetPath];
    
    if(!success)
    {
        //如果不存在，则读取脚本文件，进行数据库创建
        FMDatabase *initDB = nil;
        @try
        {
            //创建数据库文件
            initDB = [[FMDatabase alloc]initWithPath:dbTargetPath];
            [initDB open];
            NSString *sqlData = nil;
            NSString *respath = nil;
            respath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sql"];
            NSData *data = [fileManager contentsAtPath:respath];
            sqlData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSArray *sqls = nil;
            sqls = [sqlData componentsSeparatedByString:@";"];
            //执行建库脚本
            for (NSString *sql in sqls) {
                [sql stringByAppendingFormat:@"%@",@";"];
                [initDB executeUpdate:sql];
            }
                
//            respath = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"sql"];
//            data = [fileManager contentsAtPath:respath];
//            sqlData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//            sqls = [sqlData componentsSeparatedByString:@";"];
//            //执行初始化脚本
//            for (NSString *sql in sqls) {
//                [sql stringByAppendingFormat:@"%@",@";"];
//                [initDB executeUpdate:sql];
//            }
            
            [sqls release];
            [sqlData release];
            [data release];
            
        }@catch (NSException *exception) {
            NSLog(@"Create db connection error :[name] %@,[reasion] %@",[exception name],[exception reason]);
        }
        @finally {
            [initDB close];
            [initDB release];
        }
        
    }else
    {
        //如果存在，则判断数据库表结构是否完整
    }

    [fileManager release];
    self.dbPath = dbTargetPath;    
}

-(id)initSingleton
{
    //    self = [super init];
    //初始化数据库连接
    if(self = [super init])
    {

        if(nil == dbo)
        {
            
            [self initAppDataBase];
            
            @try {
                if(nil == dbo)
                {
                    static dispatch_once_t pred;
                    dispatch_once(&pred, ^{
                        dbo = [[FMDatabase alloc]initWithPath:_dbPath];
                    });        
                    [dbo open];
                }

            }
            @catch (NSException *exception) {
                NSLog(@"Create db connection error :[name] %@,[reasion] %@",[exception name],[exception reason]);
            }
            @finally {
                
            }
        }
    }

    return self;
}

#pragma mark - single instance 
+(TokDataBase *)sharedInstanceMethod
{
    if(sharedInstance != nil)
    {
        return sharedInstance;
    }
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        sharedInstance = [[TokDataBase alloc] initSingleton];
    });
    return sharedInstance;

    
}

//copy返回单例本身  
- (id)copyWithZone:(NSZone *)zone  
{  
    return self;  
}  

//retain返回单例本身  
- (id)retain  
{  
    return self;  
}  

//引用计数总是为1  
- (NSUInteger)retainCount  
{  
    return INT32_MAX;  
}  

//release不做任何处理  
- (oneway void)release  
{  
    
}  

//autorelease返回单例本身  
- (id)autorelease  
{  
    return self;  
}  

//  
-(void)dealloc  
{  
    [super dealloc];  
    if(dbo)
    {
        [dbo close];
        [dbo release];
    }
} 



#pragma mark - TokDBProtocol

-(id *)insertWithObject:(NSArray *)obj
{
    return nil;
}

-(id *)deleteWithObject:(NSArray *)obj
{
     return nil;
}

-(NSArray *)queryWithObject:(Class *)obj conditionCluse:(NSString *) whereSql Columns:(NSArray *) returnColunm Orderby:(NSArray *) orderColumn sort:(int) sortModel
{
     return nil;
}

-(id *)updateWithObject:(NSMutableArray *)obj
{
     return nil;
}

-(BOOL) executeUpdate:(NSString *) sql
{
    BOOL result = YES;
    @try {
        result = [dbo executeUpdate:sql];
    }
    @catch (NSException *exception) {
        result = NO;
    }
    @finally {
        
    }
    return result;
}

-(NSArray *)executeQuery:(NSString *) sql
{
    FMResultSet *rs = nil;
    NSMutableArray *result = nil;
    @try {
        rs = [dbo executeQuery:sql];
        result = [[NSMutableArray alloc]init];
        int colcount = [rs columnCount];
        int rowcount = 0;
        while ([rs next]) {
            NSMutableDictionary *row = [[NSMutableDictionary alloc]init];
            for (int i = 0; i < colcount; i++) {
                NSString *columnName = [rs columnNameForIndex:i];
                [row setValue:[rs dataForColumnIndex:i] forKey:columnName];
            }
            [result insertObject:row atIndex:rowcount];
            rowcount++;
        }
    }
    @catch (NSException *exception) {

    }
    @finally {
        [rs close];
    }
    return result;


}


@end
